package com.springboot.autoconfigure.oss.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.springboot.autoconfigure.oss.model.FileUploadStatus;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

/**
 * 文件处理类
 */
public abstract class FileResolveService {


    //文件名层级分隔符号
    public static final String SPLIT_PATH = "_";
    //URL 上传指定文件名前缀
    public static final String URL_UPLOAD_PREFIX = "UPLOAD-BY-URL";
    /**
     * 文件生成 时间+uuid的文件名
     * @param file
     * @return
     */
    public String getFileNameString(File file) {
        String fileName = null;
        String extFileName = FileUtil.extName(file);
        if (StrUtil.isEmptyIfStr(extFileName)) {
            fileName = FileUtil.mainName(file) + SPLIT_PATH + getFileDate() + SPLIT_PATH + UUID.randomUUID();
        } else {
            fileName = FileUtil.mainName(file) + SPLIT_PATH + getFileDate() + SPLIT_PATH + UUID.randomUUID() + "." + extFileName;
        }
        return fileName;
    }

    private String getFileDate() {
        return DatePattern.PURE_DATETIME_MS_FORMAT.format(new Date());
    }


    /**
     * 根据url地址获取 本地下载文件并上传
     * @param url
     * @return
     */
    public static synchronized File getFileByUrl(URL url){
        String tmpDirPath = FileUtil.getTmpDirPath();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(tmpDirPath);
        stringBuilder.append(File.separator);
        stringBuilder.append(new Date().getTime());
        stringBuilder.append("_"+UUID.randomUUID().toString());
        String extension = FilenameUtils.getExtension(url.getPath());
        String name = FilenameUtils.getName(url.getPath());

        //optional
        Optional<String> userOptional = Optional.ofNullable(extension);
        userOptional.map(item->stringBuilder.append(".").append(item)).orElse(stringBuilder.append(""));
        File tmpFile = new File(stringBuilder.toString());
        try {
            FileUtils.copyURLToFile(url,tmpFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File absoluteFile = tmpFile.getAbsoluteFile();
        System.out.println(absoluteFile.getAbsoluteFile());
        return tmpFile;
    }


    public abstract void getUploadUrl(FileUploadStatus fileUploadStatus,String uploadResponseInfo);


}
